package com.block.source.service.receive;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.BaseTypeInfoEnum;
import com.block.common.enums.InfoTypeEnum;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.service.IAddressInfoService;
import com.block.common.service.IApplicationInfoService;
import com.block.common.service.IChannelCommonService;
import com.block.db.entity.*;
import com.block.db.mapper.SourcePushResultInfoMapper;
import com.block.source.model.api.XinXiaoRongParam;
import com.block.source.model.dto.SourceApiParam;
import com.block.source.model.dto.SourceApiResult;
import com.block.source.model.param.UserDataParam;
import com.block.source.service.ISourceReceiveService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class XinXiaoRongReceiveService extends ISourceReceiveService {

    @Autowired
    IAddressInfoService addressInfoService;
    @Resource
    SourcePushResultInfoMapper sourcePushResultInfoMapper;
    @Autowired
    IChannelCommonService channelCommonService;
    @Autowired
    IApplicationInfoService applicationInfoService;


    @Override
    public SourceApiResult handleCheckUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {
        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecretSubstring = sourceBaseInfo.getApiSecret().substring(0, 16);

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息为空"));
            return sourceApiResult;
        }
        String content = jsonObjectParamContent.getString("content");
        String paramContentData = SecureUtil.aes(apiSecretSubstring.getBytes()).decryptStr(content);
        JSONObject jsonObject = JSONObject.parseObject(paramContentData);
        //过滤
        if (StrUtil.isEmpty(jsonObject.getString("apply_name")) || StrUtil.isEmpty(jsonObject.getString("loan_term")) || StrUtil.isEmpty(jsonObject.getString("credit_card_limit")) || StrUtil.isEmpty(jsonObject.getString("huabei")) || StrUtil.isEmpty(jsonObject.getString("professional")) || StrUtil.isEmpty(jsonObject.getString("equipment"))){
            sourceApiResult.setReturnObject(this.getError("撞库传入的信息有空值"));
            return sourceApiResult;
        }

        UserDataParam userDataParam = this.getUserDataParam(paramContentData);


        // 通过城市编码,获取城市信息
        AddressInfo addressInfo = addressInfoService.getAddressInfoByCityCode(userDataParam.getCityCode());
        if (ObjectUtil.isEmpty(addressInfo)) {
            sourceApiResult.setReturnObject(this.getError("城市信息为空"));
            return sourceApiResult;
        }

        // 设置省市信息
        userDataParam.setCityCode(addressInfo.getCityCode());
        userDataParam.setCity(addressInfo.getCity());
        userDataParam.setProvinceCode(addressInfo.getProvinceCode());
        userDataParam.setProvince(addressInfo.getProvince());



        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult handleRegisterUserData(SourceBaseInfo sourceBaseInfo, Map<String, String[]> parameterMap, String paramContent) {

        SourceApiResult sourceApiResult = new SourceApiResult();
        sourceApiResult.setSuccess(false);

        String apiSecretSubstring = sourceBaseInfo.getApiSecret().substring(0, 16);

        JSONObject jsonObjectParamContent = JSONObject.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObjectParamContent)){
            sourceApiResult.setReturnObject(this.getError("进件传入的信息为空"));
            return sourceApiResult;
        }
        String content = jsonObjectParamContent.getString("content");
        String paramContentData = SecureUtil.aes(apiSecretSubstring.getBytes()).decryptStr(content);

        XinXiaoRongParam xinXiaoRongParam = JSON.parseObject(paramContentData, XinXiaoRongParam.class);

        UserDataParam userDataParam = this.getUserDataParam(paramContentData);

        userDataParam.setMobile(xinXiaoRongParam.getPhone());
        userDataParam.setRealName(xinXiaoRongParam.getApply_name());

        String productId = xinXiaoRongParam.getProduct_id();
        SourcePushResultInfo pushResultInfo = sourcePushResultInfoMapper.selectByChannelCodeAndOutOrderNo(sourceBaseInfo.getChannelCode(), productId);
        userDataParam.setOrderNo(String.valueOf(pushResultInfo.getId()));

        sourceApiResult.setUserDataParam(userDataParam);
        sourceApiResult.setSuccess(true);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getCheckUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO, SourceApiParam sourceApiParam) {


        SourceApiResult sourceApiResult = new SourceApiResult();

        MerchantBaseInfo merchantBaseInfo = sourceApiParam.getMerchantBaseInfo();
        SourcePushResultInfo pushResultInfo = sourceApiParam.getSourcePushResultInfo();
        MerchantThirdBaseInfo thirdBaseInfo = sourceApiParam.getThirdBaseInfo();
        List<MerchantThirdProtocolInfo> thirdProtocolInfoList = sourceApiParam.getThirdProtocolInfoList();

        JSONObject returnObject = new JSONObject();
        returnObject.put("status", 200);
        returnObject.put("msg", "匹配成功！");
        JSONObject dataObject = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        dataObject.put("product_id", pushResultInfo.getOutOrderNo());
        if (StrUtil.equals(merchantBaseInfo.getInfoType(), InfoTypeEnum.APIS.getValue())){
            // 下游是 非 apis 类型
            dataObject.put("institution_name", thirdBaseInfo.getCompanyName());
            String companyLogo = thirdBaseInfo.getCompanyLogo();
            if (StringUtils.isEmpty(companyLogo)){
                dataObject.put("logo", "");
            }else {
                dataObject.put("logo", companyLogo);
            }
            dataObject.put("product_name", thirdBaseInfo.getProductName());
            //协议地址
            for (MerchantThirdProtocolInfo protocolInfo : thirdProtocolInfoList) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("protocolName",protocolInfo.getProtocolName());
                jsonObject.put("protocolUrl", protocolInfo.getProtocolUrl());
                jsonArray.add(jsonObject);
            }
        }else {
            dataObject.put("institution_name", merchantBaseInfo.getCompanyName());
            String companyLogo = merchantBaseInfo.getCompanyLogo();
            if (StringUtils.isEmpty(companyLogo)){
                dataObject.put("logo", "");
            }else {
                dataObject.put("logo", merchantBaseInfo.getCompanyLogo());
            }
            dataObject.put("product_name", merchantBaseInfo.getInfoName());
            //协议地址
            JSONObject jsonObject = new JSONObject();
            ChannelBaseInfo baseInfoByCode = channelCommonService.getBaseInfoByCode(sourceBaseInfo.getChannelCode());
            ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(baseInfoByCode.getAppCode());
            String protocolUrl = StrUtil.format("{}/page/newprotocol/{}/{}.html", appInfoByAppCode.getApiUrl(), pushResultInfo.getOrderNo(), pushResultInfo.getOrderItemNo());
            jsonObject.put("protocolName","授权协议");
            jsonObject.put("protocolUrl", protocolUrl);
            jsonArray.add(jsonObject);
        }

        dataObject.put("protocol_list", jsonArray);
        returnObject.put("data", dataObject);
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public SourceApiResult getRegisterUserReturnData(SourceBaseInfo sourceBaseInfo, ResultInfoVO resultInfoVO,SourceApiParam sourceApiParam) {
        SourceApiResult sourceApiResult = new SourceApiResult();

        JSONObject returnObject = new JSONObject();

        JSONObject data = resultInfoVO.getData();
        String respCode = resultInfoVO.getRespCode();

        if (StrUtil.equals(respCode, "200") && resultInfoVO.isSuccess()){
            String status = data.getString("status");
            if (StrUtil.equals(status, "000")){
                returnObject = this.getSuccess();
                returnObject.put("data",new JSONObject());
                sourceApiResult.setReturnObject(returnObject);
                return sourceApiResult;
            }
        }

        returnObject = this.getError("推送失败");
        returnObject.put("data",new JSONObject());
        sourceApiResult.setReturnObject(returnObject);

        return sourceApiResult;
    }

    @Override
    public JSONObject getError(String message) {
        JSONObject returnObject = new JSONObject();
        returnObject.put("status", 500);
        returnObject.put("msg", message);
        return returnObject;
    }

    @Override
    public JSONObject getSuccess() {
        JSONObject returnObject = new JSONObject();
        returnObject.put("status", 200);
        returnObject.put("msg", "推送成功");
        return returnObject;
    }

    @Override
    public UserDataParam getUserDataParam(String paramContent) {

        XinXiaoRongParam xinXiaoRongParam = JSON.parseObject(paramContent, XinXiaoRongParam.class);

        UserDataParam userDataParam = new UserDataParam();

        Integer randomInt = RandomUtil.randomInt(Integer.MAX_VALUE);
        userDataParam.setOutOrderNo(String.valueOf(randomInt));

        userDataParam.setMobileMd5(xinXiaoRongParam.getPhone_md5());
        userDataParam.setMobile(xinXiaoRongParam.getPhone());
        userDataParam.setRealName(xinXiaoRongParam.getApply_name());

        if ("0".equals(xinXiaoRongParam.getSex())){
            userDataParam.setSex("1");
        }else {
            userDataParam.setSex("2");
        }


        userDataParam.setAge(Integer.valueOf(xinXiaoRongParam.getAge()));
        userDataParam.setCityCode(xinXiaoRongParam.getProvince());


        String creditCardLimit = xinXiaoRongParam.getCredit_card_limit();
        if ("0".equals(creditCardLimit)){
            userDataParam.setXinyongka(BaseTypeInfoEnum.XinYongKa.xyk001.getValue());
        }else {
            userDataParam.setXinyongka(BaseTypeInfoEnum.XinYongKa.xyk002.getValue());
        }

        userDataParam.setYongtu(BaseTypeInfoEnum.Yongtu.yt007.getValue());
        userDataParam.setXueli(BaseTypeInfoEnum.XueLi.xl001.getValue());
        userDataParam.setShouru(BaseTypeInfoEnum.Shouru.sr001.getValue());
        userDataParam.setWeili(BaseTypeInfoEnum.WeiLi.wl001.getValue());
        userDataParam.setBaitiao(BaseTypeInfoEnum.Baitiao.bt001.getValue());
        userDataParam.setHuabei(BaseTypeInfoEnum.Huabei.hb001.getValue());
        String huabei = xinXiaoRongParam.getHuabei();
        if ("0".equals(huabei)){
            userDataParam.setHuabei(BaseTypeInfoEnum.Huabei.hb001.getValue());
        }else {
            userDataParam.setHuabei(BaseTypeInfoEnum.Huabei.hb003.getValue());
        }
        userDataParam.setUserIp("127.0.0.1");

        String loan = xinXiaoRongParam.getLoan();
        if (Integer.valueOf(loan) == Integer.valueOf("3")) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la001.getValue());
        } else if (Integer.valueOf(loan) == Integer.valueOf("5")) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la002.getValue());
        } else if (Integer.valueOf(loan) == Integer.valueOf("10")) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la003.getValue());
        } else if (Integer.valueOf(loan) == Integer.valueOf("20")) {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la004.getValue());
        } else {
            userDataParam.setLoanAmount(BaseTypeInfoEnum.LoanAmount.la005.getValue());
        }

        String houseProperty = xinXiaoRongParam.getHouse_property();
        if ("0".equals(houseProperty)){
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu001.getValue());
        }else if ("1".equals(houseProperty)){
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu004.getValue());
        }else {
            userDataParam.setHouse(BaseTypeInfoEnum.House.hu003.getValue());
        }

        userDataParam.setBaoxian(BaseTypeInfoEnum.Baoxian.bx002.getValue());


        userDataParam.setYuqi(BaseTypeInfoEnum.Yuqi.yq001.getValue());

        String hasFund = xinXiaoRongParam.getHas_fund();
        if ("0".equals(hasFund)){
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj001.getValue());
        }else if ("2".equals(hasFund)){
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj002.getValue());
        }else {
            userDataParam.setGjj(BaseTypeInfoEnum.Gjj.gjj003.getValue());
        }

        String zhimaCredit = xinXiaoRongParam.getZhima_credit();
        if ("6".equals(zhimaCredit)){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm005.getValue());
        }else if ("5".equals(zhimaCredit)){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm004.getValue());
        }else if ("4".equals(zhimaCredit)){
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm003.getValue());
        }else{
            userDataParam.setZhima(BaseTypeInfoEnum.Zhima.zm002.getValue());
        }

        String hasSocial = xinXiaoRongParam.getHas_social();
        if ("0".equals(hasSocial)){
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb001.getValue());
        }else if ("2".equals(hasSocial)){
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb002.getValue());
        }else {
            userDataParam.setShebao(BaseTypeInfoEnum.Shebao.sb003.getValue());
        }

        String carProperty = xinXiaoRongParam.getCar_property();
        if ("0".equals(carProperty)){
            userDataParam.setCar(BaseTypeInfoEnum.Car.car001.getValue());
        }else if ("2".equals(carProperty)){
            userDataParam.setCar(BaseTypeInfoEnum.Car.car002.getValue());
        }else {
            userDataParam.setCar(BaseTypeInfoEnum.Car.car003.getValue());
        }

        String professional = xinXiaoRongParam.getProfessional();
        if ("0".equals(professional)){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz001.getValue());
        }else if ("1".equals(professional)){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz002.getValue());
        }else if ("3".equals(professional)){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz003.getValue());
        }if ("4".equals(professional)){
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz004.getValue());
        }else{
            userDataParam.setGongzuo(BaseTypeInfoEnum.Gongzuo.gz005.getValue());
        }

        String loanTerm = xinXiaoRongParam.getLoan_term();
        if (Integer.valueOf("12") == Integer.valueOf(loanTerm) || Integer.valueOf("24") == Integer.valueOf(loanTerm) || Integer.valueOf("36") == Integer.valueOf(loanTerm)){
            userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt004.getValue());
        }else if (Integer.valueOf("6") == Integer.valueOf(loanTerm)){
            userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt003.getValue());
        }else if (Integer.valueOf("3") == Integer.valueOf(loanTerm)){
            userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt002.getValue());
        }else {
            userDataParam.setLoanTime(BaseTypeInfoEnum.LoanTime.lt001.getValue());
        }


        return userDataParam;
    }

}
